package cn.qfei.qiyuesuo.service.feishu.impl;

import cn.qfei.qiyuesuo.bo.ClientModel;
import cn.qfei.qiyuesuo.service.feishu.FeishuImService;
import cn.qfei.qiyuesuo.service.feishu.util.FeishuClientUtils;
import cn.qfei.qiyuesuo.vo.FeishuContractVo;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.lark.oapi.Client;
import com.lark.oapi.core.request.FormData;
import com.lark.oapi.core.request.RequestOptions;
import com.lark.oapi.core.response.RawResponse;
import com.lark.oapi.core.token.AccessTokenType;
import com.lark.oapi.core.utils.Jsons;
import com.lark.oapi.core.utils.Lists;
import com.lark.oapi.service.approval.v4.model.*;
import com.lark.oapi.service.bitable.v1.model.SearchAppTableRecordReq;
import com.lark.oapi.service.bitable.v1.model.SearchAppTableRecordReqBody;
import com.lark.oapi.service.bitable.v1.model.SearchAppTableRecordResp;
import com.lark.oapi.service.im.v1.model.CreateMessageReq;
import com.lark.oapi.service.im.v1.model.CreateMessageReqBody;
import com.lark.oapi.service.im.v1.model.CreateMessageResp;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class FeishuImServiceImp implements FeishuImService {

    public int tasksApprov(String approvalCode,String instanceCode,String userId,String taskId,String fsFileId, String appId,String appSecret, String form)  {
        // 构建client
        Client client = Client.newBuilder("YOUR_APP_ID", "YOUR_APP_SECRET").build();
//        List<Map<String,String>> list=new ArrayList<>();
//        Map<String,String> map=new HashMap<>();
//        map.put("fileId",fsFileId);
//        list.add(map);
        String formStr=form;
        log.info("from={}",formStr);
        // 创建请求对象
        ApproveTaskReq req = ApproveTaskReq.newBuilder()
                .taskApprove(TaskApprove.newBuilder()
                        .approvalCode(approvalCode)
                        .instanceCode(instanceCode)
                        .userId(userId)
                        .comment("OK")
                        .taskId(taskId)
                        .form(formStr)
                        .build())
                .build();

        // 发起请求
        ApproveTaskResp resp = null;
        try {
            resp = client.approval().task().approve(req);
        } catch (Exception e) {
            log.error("出错",e);
        }

        // 处理服务端错误
        if(!resp.success()) {
            System.out.println(String.format("code:%s,msg:%s,reqId:%s", resp.getCode(), resp.getMsg(), resp.getRequestId()));
            return 0;
        }
        return 1;
        // 业务数据处理
    }

    @Override
    public  byte[] downloadFile(String fileId, String appId, String appSecret) {



        Client client = Client.newBuilder(appId, appSecret).build();

        // 创建请求对象

        // 发起请求
        RawResponse resp = null;
        try {
            resp = client.get("/open-apis/contract/v1/files/"+fileId, null, AccessTokenType.Tenant);
        } catch (Exception e) {
            log.error("调飞书出错",e);
        }

        // 业务数据处理
        System.out.println(resp.getStatusCode());
        System.out.println(Jsons.DEFAULT.toJson(resp.getHeaders()));
        System.out.println(resp.getRequestID());
        return resp.getBody();
    }

    /**
     * 获取单个审批实例详情
     * @param instanceId
     * @param appId
     * @param appSecret
     * @return
     */
    public Map<String, Object> selectInstanceById(String instanceId,String appId, String appSecret) {
        Client client = getClint(appId,appSecret,null);


        // 创建请求对象
        if (! StringUtils.isBlank(instanceId)){
            //https://open.feishu.cn/open-apis/contract/v1/contracts/:contract_id
            //process_instance_id  流程实例id  process_instance_id
            RawResponse resp = null;
            try {
                resp = client.get(
                        "/open-apis/approval/v4/instances/"+instanceId, null,
                        AccessTokenType.Tenant, RequestOptions.newBuilder()
                                // 如开启了Sdk的token管理功能，就无需调用 RequestOptions.newBuilder().tenantAccessToken("t-xxx").build()来设置租户token了
//                                .tenantAccessToken(tenantAccessToken)
                                .build());
            } catch (Exception e) {
                log.error("数据出错",e);
            }finally {
                log.info("获取飞书合同 statusCode={},headers={}, body={},requestId={}",resp.getStatusCode(),
                        Jsons.DEFAULT.toJson(resp.getHeaders()),new String(resp.getBody()),resp.getRequestID());
            }

            int statusCode = resp.getStatusCode();
            if (statusCode != 200){
                log.error("获取合同数据异常，code={},异常信息={},requestId={}", resp.getStatusCode(),new String(resp.getBody()), resp.getRequestID());
                return null;
            }
            String data = new String(resp.getBody());
            FeishuContractVo feishuContractVo = JSONObject.parseObject(data, FeishuContractVo.class);
            boolean success = feishuContractVo.isSuccess();
            if (! success){
                return null;
            }
            Map<String, Object> contractVoData = feishuContractVo.getData();
            return contractVoData;
        }
        return null;
    }


    @Override
    public int updateContract(String contractId, String appId, String appSecret, List<String> attachmentIds) {
        Client client = getClint(appId,appSecret,null);





        //封装发送结构体
        RawResponse resp = null;

        Map<String,Object> map=new HashMap<>();
        map.put("archive_attachment_fields",attachmentIds);


        try {
            resp = client.patch(
                    "/open-apis/contract/v1/contracts/"+contractId, map,
                    AccessTokenType.Tenant, RequestOptions.newBuilder()
                            // 如开启了Sdk的token管理功能，就无需调用 RequestOptions.newBuilder().tenantAccessToken("t-xxx").build()来设置租户token了
//                                .tenantAccessToken(tenantAccessToken)
                            .build());

            int statusCode = resp.getStatusCode();
            if (statusCode != 200){
                log.error("获取合同数据异常，code={},异常信息={},requestId={}", resp.getStatusCode(),new String(resp.getBody()), resp.getRequestID());
                return 0;

            }
            String data = new String(resp.getBody(),"UTF-8");
            FeishuContractVo feishuContractVo = JSONObject.parseObject(data, FeishuContractVo.class);
            boolean success = feishuContractVo.isSuccess();
            if (! success){
                return 0;
            }
           return 1;

        } catch (Exception e) {
            log.error("出错",e);
        }finally {
            log.info("获取飞书合同 statusCode={},headers={}, body={},requestId={}",resp.getStatusCode(),
                    Jsons.DEFAULT.toJson(resp.getHeaders()),new String(resp.getBody()),resp.getRequestID());
        }

        return 0;
    }

    @Override
    public int updateInstanceAssignee(String processInstanceId, String appId, String appSecret, String taskInstanceId, String assigneeIds) {
        Client client = getClint(appId,appSecret,null);
        //封装发送结构体
        RawResponse resp = null;
        Map<String,Object> map=new HashMap<>();
        map.put("task_instance_id",taskInstanceId);
        map.put("task_comment","同意");
        map.put("assignee_id",assigneeIds);
        map.put("command_type","general");


        try {
            resp = client.post(
                    "/open-apis/contract/v1/process_instances/"+processInstanceId+"/task_approval", map,
                    AccessTokenType.Tenant, RequestOptions.newBuilder()
                            // 如开启了Sdk的token管理功能，就无需调用 RequestOptions.newBuilder().tenantAccessToken("t-xxx").build()来设置租户token了
//                                .tenantAccessToken(tenantAccessToken)
                            .build());

            int statusCode = resp.getStatusCode();
            if (statusCode != 200){
                log.error("获取合同数据异常，code={},异常信息={},requestId={}", resp.getStatusCode(),new String(resp.getBody()), resp.getRequestID());
                return 0;

            }
            String data = new String(resp.getBody(),"UTF-8");
            FeishuContractVo feishuContractVo = JSONObject.parseObject(data, FeishuContractVo.class);
            boolean success = feishuContractVo.isSuccess();
            if (! success){
                return 0;
            }
            return 1;

        } catch (Exception e) {
            log.error("出错",e);
        }finally {
            log.info("获取飞书合同 statusCode={},headers={}, body={},requestId={}",resp.getStatusCode(),
                    Jsons.DEFAULT.toJson(resp.getHeaders()),new String(resp.getBody()),resp.getRequestID());
        }

        return 0;
    }

    public Map<String, Object> selectContractById(String contractId, String appId, String appSecret) {
        Client client = getClint(appId,appSecret,null);
        if (! StringUtils.isBlank(contractId)){
            //https://open.feishu.cn/open-apis/contract/v1/contracts/:contract_id
            //process_instance_id  流程实例id  process_instance_id
            RawResponse resp = null;
            try {
                resp = client.get(
                        "/open-apis/contract/v1/contracts/"+contractId, null,
                        AccessTokenType.Tenant, RequestOptions.newBuilder()
                                // 如开启了Sdk的token管理功能，就无需调用 RequestOptions.newBuilder().tenantAccessToken("t-xxx").build()来设置租户token了
//                                .tenantAccessToken(tenantAccessToken)
                                .build());
                int statusCode = resp.getStatusCode();
                if (statusCode != 200){
                    log.error("获取合同数据异常，code={},异常信息={},requestId={}", resp.getStatusCode(),new String(resp.getBody()), resp.getRequestID());
                    return null;
                }
                String data = new String(resp.getBody(), "UTF-8");
                log.info("数据={}",data);

                FeishuContractVo feishuContractVo = JSON.parseObject(data, FeishuContractVo.class);
                boolean success = feishuContractVo.isSuccess();
                if (! success){
                    return null;
                }
                Map<String, Object> contractVoData = feishuContractVo.getData();
                return (Map<String, Object>) contractVoData.get(FeishuContractVo.CONTRACT_FIELD_KEY);
            } catch (Exception e) {
              log.error("数据出错",e);
            }finally {
                log.info("获取飞书合同 statusCode={},headers={}, body={},requestId={}",resp.getStatusCode(),
                        Jsons.DEFAULT.toJson(resp.getHeaders()),new String(resp.getBody()),resp.getRequestID());
            }


        }
        return null;
    }

    @Override
    public Map<String, Object> getFsProcessInstances(String processInstanceId, String appId, String appSecret)  {
        Client client = getClint(appId,appSecret,null);
        if (! StringUtils.isBlank(processInstanceId)){
            //https://open.feishu.cn/open-apis/contract/v1/contracts/:contract_id
            //process_instance_id  流程实例id  process_instance_id
            RawResponse resp = null;
            try {
                resp = client.get(
                        "/open-apis/contract/v1/process_instances/"+processInstanceId, null,
                        AccessTokenType.Tenant, RequestOptions.newBuilder()
                                // 如开启了Sdk的token管理功能，就无需调用 RequestOptions.newBuilder().tenantAccessToken("t-xxx").build()来设置租户token了
//                                .tenantAccessToken(tenantAccessToken)
                                .build());

                int statusCode = resp.getStatusCode();
                if (statusCode != 200){
                    log.error("获取合同数据异常，code={},异常信息={},requestId={}", resp.getStatusCode(),new String(resp.getBody()), resp.getRequestID());
                    throw new RuntimeException("服务异常，请稍后重试");
                }
                String data = new String(resp.getBody(),"UTF-8");
                FeishuContractVo feishuContractVo = JSONObject.parseObject(data, FeishuContractVo.class);
                boolean success = feishuContractVo.isSuccess();
                if (! success){
                   log.info("数据异常，请稍后重试");
                }
                Map<String, Object> contractVoData = feishuContractVo.getData();
                return (Map<String, Object>) contractVoData.get(FeishuContractVo.PROCESS_INSTANCE_KEY);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }finally {
                log.info("获取飞书合同 statusCode={},headers={}, body={},requestId={}",resp.getStatusCode(),
                        Jsons.DEFAULT.toJson(resp.getHeaders()),new String(resp.getBody()),resp.getRequestID());
            }


        }
        return null;
    }

    @Override
    public int sendCardMessageToPeople(String appId, String appSecret, String receiveId, String msgType, String content,String receiveType) {
        Client client = getClint(appId,appSecret,null);

        //为防止异常判定类型以及发送id不能为空
        if(StringUtils.isBlank(receiveId)){
            return 0;
        }
        Map<String ,Object> map=JSON.parseObject(content,Map.class);
//        Map<String ,Object> map1=new HashMap<>();
//        Map<String ,Object> map2=new HashMap<>();
//        map1.put("data","map2");
//        map2.put("template_id","ctp_AAkIyouJa5NR");
//
//        Map<String ,Object> map3=new HashMap<>();
//        map2.put("template_variable",map3);
//
//        map1.put("text",map2);
        log.info("入参receiveId={}，",receiveId);
        log.info("content={}",content);
        Map<String ,Object> map1=(Map<String ,Object>)map.get("content");
//        msgType="text";
        //封装发送结构体
        CreateMessageReqBody createMessageReqBody=CreateMessageReqBody.newBuilder()
                .content(JSON.toJSONString(map1))
                .msgType(msgType)
                .receiveId(receiveId)
                .build();

        // 创建请求对象
        CreateMessageReq req = CreateMessageReq.newBuilder()
                .receiveIdType(receiveType)
                .createMessageReqBody(createMessageReqBody)
                .build();
        CreateMessageResp rsp = null;
        try {
            //请求飞书底座创建消息卡片并发送指定人
            rsp = client.im().message().create(req);
            log.info(JSON.toJSONString(rsp));
            return 1;

        } catch (Exception e) {
            log.error("请求飞书消息卡片发送指定人API时出现异常:{}", e.getMessage());
        }
        // 处理服务端错误
        if (!rsp.success()) {
            log.error("请求飞书消息卡片发送指定人API时出现异常:{}", createMessageReqBody.getContent() );
        }
        return 0;
    }
//
    @Override
    public String uploadContractFile(String contractId, String appId, String appSecret, String fileType, File file, String fileName) {
        Client client = getClint(appId,appSecret,null);
        //封装发送结构体
        RawResponse resp = null;
        try {

            FormData body = new FormData();
            body.addFile("file", file);
            body.addField("file_type", fileType);
            body.addField("file_name", fileName);


            resp = client.post(
                    "/open-apis/contract/v1/files/upload", body,
                    AccessTokenType.Tenant, RequestOptions.newBuilder()
                            // 如开启了Sdk的token管理功能，就无需调用 RequestOptions.newBuilder().tenantAccessToken("t-xxx").build()来设置租户token了
//                                .tenantAccessToken(tenantAccessToken)
                            .build());


            int statusCode = resp.getStatusCode();
            if (statusCode != 200){
                log.error("获取合同数据异常，code={},异常信息={},requestId={}", resp.getStatusCode(),new String(resp.getBody()), resp.getRequestID());
                return null;

            }
            String data = new String(resp.getBody());
            FeishuContractVo feishuContractVo = JSONObject.parseObject(data, FeishuContractVo.class);
            boolean success = feishuContractVo.isSuccess();
            if (! success){
                return null;
            }
            Map<String, Object> contractVoData = feishuContractVo.getData();
            if (contractVoData.get("file_id")==null){
                return null;
            }
            return contractVoData.get("file_id").toString();


        } catch (Exception e) {
            log.error("出错",e);
        }finally {
            log.info("获取飞书合同 statusCode={},headers={}, body={},requestId={}",resp.getStatusCode(),
                    Jsons.DEFAULT.toJson(resp.getHeaders()),new String(resp.getBody()),resp.getRequestID());
        }

        return null;
    }

    /**
     * 审批文件上传
     * @param contractId
     * @param appId
     * @param appSecret
     * @param fileType
     * @param file
     * @param fileName
     * @return
     */
    @Override
    public String uploadApprovalFile(String contractId, String appId, String appSecret, String fileType, File file, String fileName) {
        Client client = getClint(appId,appSecret,null);
        //封装发送结构体
        RawResponse resp = null;
        try {

            FormData body = new FormData();
            body.addFile("content", file);
            body.addField("type", fileType);
            body.addField("name", fileName);
            resp = client.post(
                    "/approval/openapi/v2/file/upload", body,
                    AccessTokenType.Tenant, RequestOptions.newBuilder()
                            // 如开启了Sdk的token管理功能，就无需调用 RequestOptions.newBuilder().tenantAccessToken("t-xxx").build()来设置租户token了
                            .build());

            int statusCode = resp.getStatusCode();
            if (statusCode != 200){
                log.error("获取合同数据异常，code={},异常信息={},requestId={}", resp.getStatusCode(),new String(resp.getBody()), resp.getRequestID());
                return null;

            }
            String data = new String(resp.getBody());
            FeishuContractVo feishuContractVo = JSONObject.parseObject(data, FeishuContractVo.class);
            if (feishuContractVo.getCode()!=0){
                return null;
            }
            Map<String, Object> contractVoData = feishuContractVo.getData();
            if (contractVoData.get("code")==null){
                return null;
            }
            return contractVoData.get("code").toString();


        } catch (Exception e) {
            log.error("出错",e);
        }finally {
            log.info("获取飞书合同 statusCode={},headers={}, body={},requestId={}",resp.getStatusCode(),
                    Jsons.DEFAULT.toJson(resp.getHeaders()),new String(resp.getBody()),resp.getRequestID());
        }

        return null;
    }
    public static void main(String arg[]) throws Exception {
        //7361688403563479050
        // 构建client
//        Client client = Client.newBuilder("cli_a6a20a2d3bf0500b", "O2mRguYNkppc816M99U3VccYYdOIabAY").build();
//
//        // 创建请求对象
//        Map < String, Object > body = new HashMap<>();
//        body.put("user_id_type","user_id");
//
//        // 发起请求
//        RawResponse resp = client.post(
//                "/open-apis/contract/v1/contracts/search", body, AccessTokenType.Tenant);
//
//        // 业务数据处理
//        System.out.println(resp.getStatusCode());
//        System.out.println(Jsons.DEFAULT.toJson(resp.getHeaders()));
//        System.out.println(new String(resp.getBody()));
//        System.out.println(resp.getRequestID());


        Client client = Client.newBuilder("cli_a6a20a2d3bf0500b", "O2mRguYNkppc816M99U3VccYYdOIabAY").build();

        // 创建请求对象
        // 创建请求对象
        String bodyJsonStr = "{\"page_size\":10}";
        Map < String, Object > body = Jsons.DEFAULT.fromJson(bodyJsonStr, Map.class);
//        Map < String, Object > body = Jsons.DEFAULT.fromJson(bodyJsonStr, Map.class);


        // 发起请求
        RawResponse resp = client.post(
                "/open-apis/contract/v1/contracts/search", null, AccessTokenType.Tenant);

        // 业务数据处理
        System.out.println(resp.getStatusCode());
        System.out.println(Jsons.DEFAULT.toJson(resp.getHeaders()));
        System.out.println(new String(resp.getBody()));
        System.out.println(resp.getRequestID());
    }
    public static void main2(String arg[]) throws Exception {


        Client client = Client.newBuilder("cli_a6a7098f1f2d100b", "G1io7ICpCRMTm6FMn18FjcpewBoAwgbv").build();

        // 创建请求对象
        SearchAppTableRecordReq req = SearchAppTableRecordReq.newBuilder()
                .appToken("AyYlbzFcpaUVIpsrNDVcmSMKnNf")
                .tableId("tbl9xLLktihZDwxS")
                .searchAppTableRecordReqBody(SearchAppTableRecordReqBody.newBuilder()
                        .automaticFields(true)
                        .build())
                .build();

        // 发起请求
        SearchAppTableRecordResp resp = client.bitable().appTableRecord().search(req);

        // 处理服务端错误
        if(!resp.success()) {
            System.out.println(String.format("code:%s,msg:%s,reqId:%s", resp.getCode(), resp.getMsg(), resp.getRequestId()));
            return;
        }

        // 业务数据处理
        System.out.println(Jsons.DEFAULT.toJson(resp.getData()));


//        2024-04-26 07:53:30.098  INFO 16460 --- [nio-8081-exec-2] c.q.q.s.impl.FeishuNoticeServiceImpl     : 审批信息=
//        {"biz_key":"7361688403563479050#0",
//        "end_time":"","initiator_id":"ou_d93048a284fae018bf4bbeeabe6472d5",
//        "instance_status":"RUNNING","latest_process_event_sequence_id":2002281,
//        "process_definition_id":"clm_0_7270810696940814390:26:50dc94f0-3340-4c0c-8042-3435ad39297f", 流程定义id
//        "process_definition_key":"clm_0_7270810696940814390",
//        "process_instance_id":"3dbfae25-82d9-4c97-b38b-91619c32727c"   流程实例id
//        ,"process_name":{"en":"测试流程","ja":"测试流程","zh":"测试流程"},
//        "process_subject":{"en":"Contract name: 20240401测试合同2 \nContract no.: HTCSZYTEST202404250400\nContract type:
//        合同测试专用/TEST","zh":"合同名称：20240401测试合同2 \n合同编号：HTCSZYTEST202404250400 \n合同类型：合同测试专用/TEST"},
//        "start_time":"1714031926000",
//        "task_instance_list":[{"app_url":"https://applink.feishu.cn/client/mini_program/open?appId=cli_9f4687e5517c900d&mode=window&path=pages%2Fbot%2Findex%3FredirectType%3Dshare%26taskInstanceId%3D91421367-938f-4b1d-90a3-6b77d258b912%26businessId%3D7361688403563479050%26businessTypeCode%3D0%26mode%3DdetailPage","assignee_ids":["ou_e33900c7fdb13cd5f0e47e28eda07ec4"],"create_time":"1714033695000","end_time":"","form_url":"https://contract.feishu.cn/bot?redirectType=share&taskInstanceId=
//        91421367-938f-4b1d-90a3-6b77d258b912&businessId=7361688403563479050&businessTypeCode=0&mode=detailPage","node_id":"UserTask_archive_0:3","node_name":{"en":"归档节点","ja":"归档节点","zh":"归档节点"},"
//        task_instance_id":"91421367-938f-4b1d-90a3-6b77d258b912"},{"app_url":"https://applink.feishu.cn/client/mini_program/open?appId=cli_9f4687e5517c900d&mode=window&path=pages%2Fbot%2Findex%3FredirectType%3Dshare%26taskInstanceId%3Dfeee5b08-2f29-457a-8d6e-b6020abc48c0%26businessId%3D7361688403563479050%26businessTypeCode%3D0%26mode%3DdetailPage","assignee_ids":["ou_d93048a284fae018bf4bbeeabe6472d5"],"create_time":"1714033695000","end_time":"","form_url":"https://contract.feishu.cn/bot?redirectType=share&taskInstanceId=feee5b08-2f29-457a-8d6e-b6020abc48c0&businessId=7361688403563479050&businessTypeCode=0&mode=detailPage","node_id":"UserTask_archive_0:3","node_name":{"en":"归档节点","ja":"归档节点","zh":"归档节点"},
//        "task_instance_id":"feee5b08-2f29-457a-8d6e-b6020abc48c0"},{"app_url":"https://applink.feishu.cn/client/mini_program/open?appId=cli_9f4687e5517c900d&mode=window&path=pages%2Fbot%2Findex%3FredirectType%3Dshare%26taskInstanceId%3Dd2655769-e646-463d-a683-a12104aa7acd%26businessId%3D7361688403563479050%26businessTypeCode%3D0%26mode%3DdetailPage","assignee_ids":["ou_059b5c994a2f83e8ae8b832afa7e5431"],"command_type":"general","create_time":"1714033634000","end_time":"1714033695000","form_url":"https://contract.feishu.cn/bot?redirectType=share&taskInstanceId=d2655769-e646-463d-a683-a12104aa7acd&businessId=7361688403563479050&businessTypeCode=0&mode=detailPage","node_id":"UserTask_seal_0:2","node_name":{"en":"盖章节点","ja":"盖章节点","zh":"盖章节点"},
//        "task_instance_id":"d2655769-e646-463d-a683-a12104aa7acd"},{"app_url":"https://applink.feishu.cn/client/mini_program/open?appId=cli_9f4687e5517c900d&mode=window&path=pages%2Fbot%2Findex%3FredirectType%3Dshare%26taskInstanceId%3Da88697cd-af52-4f46-8745-1debc6804492%26businessId%3D7361688403563479050%26businessTypeCode%3D0%26mode%3DdetailPage","assignee_ids":["ou_059b5c994a2f83e8ae8b832afa7e5431"],"command_type":"general","create_time":"1714031960000","end_time":"1714033633000","form_url":"https://contract.feishu.cn/bot?redirectType=share&taskInstanceId=a88697cd-af52-4f46-8745-1debc6804492&businessId=7361688403563479050&businessTypeCode=0&mode=detailPage","node_id":"UserTask_approve_0:1","node_name":{"en":"审批节点","ja":"审批节点","zh":"审批节点"},"task_instance_id":"a88697cd-af52-4f46-8745-1debc6804492"},{"app_url":"https://applink.feishu.cn/client/mini_program/open?appId=cli_9f4687e5517c900d&mode=window&path=pages%2Fbot%2Findex%3FredirectType%3Dshare%26taskInstanceId%3Dcf931bf6-4a70-493a-bfc6-b92ab746d432%26businessId%3D7361688403563479050%26businessTypeCode%3D0%26mode%3DdetailPage","assignee_ids":["ou_d93048a284fae018bf4bbeeabe6472d5"],"command_type":"general","create_time":"1714031927000","end_time":"1714031960000","form_url":"https://contract.feishu.cn/bot?redirectType=share&taskInstanceId=cf931bf6-4a70-493a-bfc6-b92ab746d432&businessId=7361688403563479050&businessTypeCode=0&mode=detailPage","node_id":"UserTask_approve_0:1","node_name":{"en":"审批节点","ja":"审批节点","zh":"审批节点"},"task_comment":"测试","task_instance_id":"cf931bf6-4a70-493a-bfc6-b92ab746d432"},{"app_url":"https://applink.feishu.cn/client/mini_program/open?appId=cli_9f4687e5517c900d&mode=window&path=pages%2Fbot%2Findex%3FredirectType%3Dshare%26taskInstanceId%3D4767d9a2-5f06-4559-945f-74db242be4b2%26businessId%3D7361688403563479050%26businessTypeCode%3D0%26mode%3DdetailPage","assignee_ids":["ou_d93048a284fae018bf4bbeeabe6472d5"],"command_type":"startandsubmit","create_time":"1714031926000","end_time":"1714031927000","form_url":"https://contract.feishu.cn/bot?redirectType=share&taskInstanceId=4767d9a2-5f06-4559-945f-74db242be4b2&businessId=7361688403563479050&businessTypeCode=0&mode=detailPage","node_id":"UserTask_submit_0:0","node_name":{"en":"提交节点","ja":"提交节点","zh":"提交节点"},"task_instance_id":"4767d9a2-5f06-4559-945f-74db242be4b2"}],"tenant_id":7233247295746310403}
//  91421367-938f-4b1d-90a3-6b77d258b912
        // 构建client
//        Client client = Client.newBuilder("cli_a6a20a2d3bf0500b", "O2mRguYNkppc816M99U3VccYYdOIabAY").build();
//
//       Map<String ,String> map=new HashMap<>();
//        map.put("text","此时发送");
//// 创建请求对象
//        CreateMessageReq req = CreateMessageReq.newBuilder()
//                .createMessageReqBody(CreateMessageReqBody.newBuilder()
//                        .receiveId("ou_d93048a284fae018bf4bbeeabe6472d5")
//                        .msgType("text")
//                        .content(JSON.toJSONString(map))
//                        .uuid("选填，每次调用前请更换，如a0d69e20-1dd1-458b-k525-dfeca4015204")
//                        .build())
//                .build();
//
//        // 发起请求
//        CreateMessageResp resp = client.im().message().create(req);
//
//        // 处理服务端错误
//        if(!resp.success()) {
//            System.out.println(String.format("code:%s,msg:%s,reqId:%s", resp.getCode(), resp.getMsg(), resp.getRequestId()));
//            return;
//        }
//
//        // 业务数据处理
//        System.out.println(Jsons.DEFAULT.toJson(resp.getData()));
    }

    public Client getClint(String appId,String appSecret,String ticket){
        if(StringUtils.isNotEmpty(ticket)){
            return  FeishuClientUtils.getIsvClient(appId, appSecret);
        }else {
            return FeishuClientUtils.getClient(appId, appSecret);
        }
    }

    public static void main1(String arg[]) throws Exception {
        // 构建client
        Client client = Client.newBuilder("cli_a6a20a2d3bf0500b", "O2mRguYNkppc816M99U3VccYYdOIabAY").build();

        // 创建请求对象
        String bodyJsonStr = "{\"combine_condition\":{\"archive_number\":\"AT20210708000030\",\"archived_time_end\":\"2021-10-01 11:11:11\",\"archived_time_start\":\"2021-10-01 11:11:11\",\"contract_category_abbreviation\":\"CUBG\",\"contract_category_name\":\"技术咨询合同\",\"contract_name\":\"合同名称\",\"contract_number\":\"CT20210708000030\",\"contract_status\":3,\"contract_status_in\":\"1,2,3\",\"form\":[{\"attribute_name\":\"受理人\",\"attribute_value\":\"6982118143107809580\",\"module_name\":\"相关单据\"}],\"owner_user_id\":\"ou_b1b355b3099b3c1fd4c937e151c4fdd5\",\"pay_type\":0,\"permission\":0,\"submited_time_end\":\"2021-10-01 11:11:11\",\"submited_time_start\":\"2021-10-01 11:11:11\",\"user_id\":\"ou_8ebd4f35d7101ffdeb4771d7c8ec517e\"},\"contract_number\":\"CT20210708000030\",\"page_size\":0,\"page_token\":\"tblKz5D60T4JlfcT\"}";
        Map < String, Object > body = Jsons.DEFAULT.fromJson(bodyJsonStr, Map.class);

        // 发起请求
        RawResponse resp = client.post(
                "/open-apis/contract/v1/contracts/search", body, AccessTokenType.Tenant);

        // 业务数据处理
        System.out.println(resp.getStatusCode());
        System.out.println(Jsons.DEFAULT.toJson(resp.getHeaders()));
        System.out.println(new String(resp.getBody()));
        System.out.println(resp.getRequestID());
    }





//    [{"anti_dated_type_code":0,"app_id":"","approved_time":"1714033634907",
//            "archive_number":"","archived_time":"","association_party":false,
//            "business_type_code":0,"business_type_name":"合同申请","complete_time":"",
//            "contract_category_abbreviation":"TEST","contract_category_name":"TEST",
//            "contract_category_number":"00A008","contract_duration":0,"contract_duration_unit":0,
//            "contract_effective_status_code":0,
//            "contract_files":{"contract_archive_attachments":[],"contract_attachments":
//        [{"download_url":"/clm/api/file/download?businessId=7361688403563479050&businessTypeCode=0&fileId=7361710731844321292&fileTypeCode=4",
//                "file_id":"7361710731844321292","file_name":"20240401测试合同1.docx",
//                "file_size":"12538","mime":"application/vnd.openxmlformats-officedocument.wordprocessingml.document"}],
//        "contract_causes":[{"download_url":"/clm/api/file/download?businessId=7361688403563479050&businessTypeCode=0&fileId=7361710718871404553&fileTypeCode=3",
//                "file_id":"7361710718871404553","file_name":"20240401测试合同3.docx","file_size":"12844",
//                "mime":"application/vnd.openxmlformats-officedocument.wordprocessingml.document"}],
//        "contract_ocr_comparisons":[],"contract_scans":[]
//        ,"contract_text":{"download_url":"/clm/api/file/download?businessId=7361688403563479050&businessTypeCode=0&fileId=7361709133973798966&fileTypeCode=2",
//                "file_id":"7361709133973798966","file_name":"20240401测试合同2.docx","file_size":"13372",
//                "mime":"application/vnd.openxmlformats-officedocument.wordprocessingml.document"}},
//        "contract_id":7361688403563479050,"" +
//                "contract_name":"20240401测试合同2","contract_number":"HTCSZYTEST202404250400",
//                "contract_status_code":8,"contract_status_name":"archiving","contract_version":1,"converted_amounts":[],
//        "counter_party_list":[{"certification_id":"91310120MA1HKGA51W","certification_name":"统一社会信用代码","certification_type":"0",
//                "certifications":[{"certification_id":"91310120MA1HKGA51W","certification_name":"统一社会信用代码","certification_type":"0",
//                "status":1}]
//            ,"counter_party_code":"V00176001","counter_party_id":"7330557452276023590",
//                    "counter_party_name":"上海亘岩网络科技有限公司","counter_party_sign_info_resource"
//            :{"date_seal_enabled":false,"date_seal_keyword":"","enable":true,"paper_seal_type_codes":"","personal_seal_enabled":false,"personal_seal_keyword":"","seal_type_codes":"2","signer_email":"","signer_mobile":"","signer_name":""},
//            "register_address":{"country":"中国大陆"},"sign_party_no":0,"trading_party_property_code":0}],
//        "create_employee_code":"034","create_employee_id":7233264268093964548,"create_time":"1714026669577",
//                "create_user_id":"ou_d93048a284fae018bf4bbeeabe6472d5","create_user_name":"张笑",
//                "department_id":"od-8cae4db99ebb14ed0c101c76df5ad2ca","department_name":"运营管理部","fixed_validity_code":0,
//                "fixed_validity_detail_code":2,"fixed_validity_detail_name":"未选择","fixed_validity_name":"不固定期限",
//                "form":"[{\"attribute_key\":\"custom_14_8c175be46a8b417a8ed8f8934d016249\",\"attribute_code\":" +
//                "\"custom_14_8c175be46a8b417a8ed8f8934d016249\",\"attribute_name\":\"印章类型\",\"attribute_type\":\"" +
//                "checkbox\",\"module_name\":\"用印说明\",\"attribute_value\":[{\"name\":\"公章\",\"key\":\"cllqabwfn004e3o6of44ixelm\"}," +
//                "{\"name\":\"骑缝章\",\"key\":\"cllqadmq9004j3o6ovbbiedfm\"},{\"name\":\"法人章\",\"key\":\"cllqabwfn004f3o6ojyltnzia\"}]}," +
//                "{\"attribute_key\":\"custom_5_c0f930792373444aa284879cbf4dc5e7\",\"attribute_code\":\"custom_5_c0f930792373444aa284879cbf4dc5e7\"" +
//                ",\"attribute_name\":\"用印份数\",\"attribute_type\":\"number\",\"module_name\":\"用印说明\",\"attribute_value\":2},{\"attribute_key\":" +
//                "\"custom_13_aa148cc91a8f4de6aa3d04aa4de0ba19\",\"attribute_code\":\"custom_13_aa148cc91a8f4de6aa3d04aa4de0ba19\",\"attribute_name\":" +
//                "\"合同用印类型\",\"attribute_type\":\"radio\",\"module_name\":\"用印说明\",\"attribute_value\":{\"name\":\"电子签约\",\"key\":\"c" +
//                "ltsftd7n000655773d4hub6v\"}},{\"attribute_key\":\"custom_1_3617bf8f8a2e402eb15f3f31728f0afc\",\"attribute_code\":\"custom_1_361" +
//                "7bf8f8a2e402eb15f3f31728f0afc\",\"attribute_name\":\"发起主体\",\"attribute_type\":\"singleline_text\",\"module_name\":\"联系信息-电子章\",\"attribute_value\":\"开弦资本管理有限公司\"},{\"attribute_key\":\"custom_1_e095ec9443e142c28e5476a78652ee74\",\"attribute_code\":\"custom_1_e095ec9443e142c28e5476a78652ee74\",\"attribute_name\":\"发起人\",\"attribute_type\":\"singleline_text\",\"module_name\":\"联系信息-电子章\",\"attribute_value\":\"张笑\"},{\"attribute_key\":\"custom_1_a55ffa5846eb42f7a4da80151175d3fe\",\"attribute_code\":\"custom_1_a55ffa5846eb42f7a4da80151175d3fe\",\"attribute_name\":\"发起人联系方式\",\"attribute_type\":\"singleline_text\",\"module_name\":\"联系信息-电子章\",\"attribute_value\":\"13680286023\"},{\"attribute_key\":\"custom_1201_270bdae4b446412abb95ec4ce703fb2c\",\"attribute_code\":\"custom_1201_270bdae4b446412abb95ec4ce703fb2c\",\"attribute_name\":\"合同签署方信息\",\"attribute_type\":\"common_array\",\"module_name\":\"联系信息-电子章\",\"attribute_value\":[[{\"attribute_key\":\"custom_1_122c0add0f27448db5012b3fd1af6738\",\"attribute_code\":\"custom_1_122c0add0f27448db5012b3fd1af6738\",\"attribute_name\":\"公司名称\",\"attribute_type\":\"singleline_text\",\"module_name\":\"联系信息-电子章\",\"row_uuid\":\"ee12fda0944f448bba6741c4fc984ac0\",\"attribute_value\":\"上海亘岩网络科技有限公司\"},{\"attribute_key\":\"custom_1_1de573c28ba6471a84c60fa79866b29c\",\"attribute_code\":\"custom_1_1de573c28ba6471a84c60fa79866b29c\",\"attribute_name\":\"接收人\",\"attribute_type\":\"singleline_text\",\"module_name\":\"联系信息-电子章\",\"row_uuid\":\"ee12fda0944f448bba6741c4fc984ac0\",\"attribute_value\":\"杨明皓\"},{\"attribute_key\":\"custom_1_ef2dc33544c24367a52f03965252f533\",\"attribute_code\":\"custom_1_ef2dc33544c24367a52f03965252f533\",\"attribute_name\":\"接收人联系方式\",\"attribute_type\":\"singleline_text\",\"module_name\":\"联系信息-电子章\",\"row_uuid\":\"ee12fda0944f448bba6741c4fc984ac0\",\"attribute_value\":\"15540028777\"}],[{\"attribute_key\":\"custom_1_122c0add0f27448db5012b3fd1af6738\",\"attribute_code\":\"custom_1_122c0add0f27448db5012b3fd1af6738\",\"attribute_name\":\"公司名称\",\"attribute_type\":\"singleline_text\",\"module_name\":\"联系信息-电子章\",\"row_uuid\":\"e884a707027b45609bad64c954e74529\",\"attribute_value\":\"开弦资本管理有限公司\"},{\"attribute_key\":\"custom_1_1de573c28ba6471a84c60fa79866b29c\",\"attribute_code\":\"custom_1_1de573c28ba6471a84c60fa79866b29c\",\"attribute_name\":\"接收人\",\"attribute_type\":\"singleline_text\",\"module_name\":\"联系信息-电子章\",\"row_uuid\":\"e884a707027b45609bad64c954e74529\",\"attribute_value\":\"秦晓君\"},{\"attribute_key\":\"custom_1_ef2dc33544c24367a52f03965252f533\",\"attribute_code\":\"custom_1_ef2dc33544c24367a52f03965252f533\",\"attribute_name\":\"接收人联系方式\",\"attribute_type\":\"singleline_text\",\"module_name\":\"联系信息-电子章\",\"row_uuid\":\"e884a707027b45609bad64c954e74529\",\"attribute_value\":\"13269892030\"}]]}]","form_id":7352805410824421426,"group_id":7361688403563495434,"info_change_version":1,"long_term_contract_remark":"","multi_url":{"mobile_url":"https://applink.feishu.cn/client/mini_program/open?appId=cli_9f4687e5517c900d&mode=window&path=pages%2Fbot%2Findex%3FredirectType%3Dshare%26taskInstanceId%3D%26businessId%3D7361688403563479050%26businessTypeCode%3D0%26mode%3DdetailPage","pc_url":"https://contract.feishu.cn/bot?redirectType=share&taskInstanceId=&businessId=7361688403563479050&businessTypeCode=0&mode=detailPage","sidebar_url":"https://applink.feishu.cn/client/web_url/open?mode=window&url=https%3A%2F%2Fcontract.feishu.cn%2Fbot%3FredirectType%3Dshare%26taskInstanceId%3D%26businessId%3D7361688403563479050%26businessTypeCode%3D0%26mode%3DdetailPage"},"our_party_list":[{"certification_id":"91110107344290021U","certification_name":"统一社会信用代码","certification_type":"0","country":"中国大陆","our_party_code":"L00101001","our_party_id":"7272634162274828604","our_party_name":"开弦资本管理有限公司","our_party_sign_info_resource":{"date_seal_enabled":false,"date_seal_keyword":"","enable":true,"paper_seal_type_codes":"","personal_seal_enabled":false,"personal_seal_keyword":"","seal_type_codes":"2","third_party_platform_info":{"third_party_platform":{},"third_party_seal_type":{}}},"sign_party_no":0}],"owner_employee_id":7233264268093964548,"owner_user_id":"ou_d93048a284fae018bf4bbeeabe6472d5","owner_user_name":"张笑","parent_contract_category_abbreviation":"HTCSZY","parent_contract_category_name":"合同测试专用","parent_contract_category_number":"00D","pay_type_code":4,"pay_type_name":"无金额","process_definition_key":"clm_0_7270810696940814390","process_instance_id":"3dbfae25-82d9-4c97-b38b-91619c32727c","property_type_code":2,"property_type_name":"无金额","remark":"测试","saas_department_id":7233258908092023099,"sign_type_code":2,"sign_type_name":"纸质签约-我方先签约","signed_time":"1714033696743","source_type_code":0,"source_type_name":"默认-上传文件","standard_framework_contract_code":0,"submitted_time":"1714031927115","submitter_employee_code":"034","submitter_employee_id":7233264268093964548,"submitter_user_id":"ou_d93048a284fae018bf4bbeeabe6472d5","submitter_user_name":"张笑","template_id":0,"terminated_time":"","update_time":"1714033696743","validity_date_desc":""}]

}
